import React, { Component } from 'react'
import store, {actions} from '../store/index'
import { NavLink } from 'react-router-dom'

export default class Redux2 extends Component {
  constructor() {
    super()
    this.state = {}
  }
  componentDidMount() {
    this.setState(store.getState());
    this.unSub = store.subscribe(()=> {
      this.setState(store.getState())
    })
  }
  componentWillUnmount() {
    // 再調用一次监听，目的是取消监听
    this.unSub()
  }
  changeAge() {
    store.dispatch(actions.add())
  }
  changeName() {
    store.dispatch(actions.changeName('Tony'))
  }
  render() {
    return (
      <div>
        <p>年龄：{this.state.age}</p>
        <p>名字：{this.state.name}</p>
        <button onClick={()=>this.changeAge()}>age+1</button>
        <button onClick={()=>this.changeName()}>修改名字</button>
        <NavLink to="redux">Redux</NavLink>
      </div>
    )
  }
}
